import Request from '@/utils/js_sdk/luch-request/luch-request/index.js' //npm下载引入luch-request
import {
	wxLogin
} from './public/index.js'
// 虚拟旅游    域名
// https://xnlv.lzxx8848.com/   // 生产
// https://xnlv.lizxx.com/  //生产
var BASE_API = 'https://xnlv.lizxx.com/api'  //生产
// var BASE_API = 'http://ccsu.lzxx8848.com/api'  //测试

const http = new Request({
	baseURL: BASE_API, //设置请求的base url
	timeout: 300000, //超时时长5分钟,
	header: {
		'Content-Type': 'multipart/form-data;application/json;charset=UTF-8;'
	}
})

//请求拦截器
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	const token = uni.getStorageSync('token');
	if (token) {
		config.header = {
			"Authorization": 'Bearer ' + token
		}
	}

	if (config.method === 'POST') {
		config.data = JSON.stringify(config.data);
	}
	return config
}, error => {
	return Promise.resolve(error)
})

// 响应拦截器
http.interceptors.response.use((response) => {
	// token过期重新获取
	if (response.data.code == 401) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
		uni.login({
			provider: 'weixin',
			success: res => {
				wxLogin(res.code, uni.getAccountInfoSync().miniProgram.appId, '', '').then(res => {
					uni.setStorageSync('token', res.data.token);
					uni.setStorageSync('wxUser', res.data.wxUser);
					uni.setStorageSync('openId', res.data.openId);
					uni.hideLoading()
				})
			},
			fail: err => {
				console.log(err)
			}
		})
	} else if (response.data.code == 500) {
		uni.showToast({
			icon: 'none',
			title: response.data.msg || '系统运行异常，工作人员正在抢修，请稍等～',
			mask: true
		})
	} else if (response.data.code == 200 || response.data.code == 600) {
		return response.data
	} else {
		uni.showToast({
			icon: 'none',
			title: response.data.msg || '系统运行异常，工作人员正在抢修，请稍等～',
			mask: true
		})
	}
}, (error) => {
	return Promise.resolve(error)
})
export default http;